﻿using Rebus.Bus;
using Rebus.Handlers;
using Serilog;
using Stee.CAP8.Saga.Sample.Message.Events;
using System.Threading.Tasks;

namespace Stee.CAP8.Saga.Sample.Stock.Handlers
{
    /// <summary>
    /// 
    /// </summary>
    public class StockHandler : IHandleMessages<StockReserveEvent>
    {
        readonly ILogger Logger = Log.ForContext<StockHandler>();
        readonly IBus _bus;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bus"></param>
        public StockHandler(IBus bus)
        {
            _bus = bus;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task Handle(StockReserveEvent message)
        {
            Logger.Information($"StockReserveEvent received for id: {message.requestID} with stock: {message.AmountOfStock}");
            if (message.AmountOfStock >= 50)
            {
                Logger.Information($"Publishing OrderStockNotAvailableEvent for order : {message.requestID}");
                await _bus.Send(new OrderStockNotAvailableEvent(message.requestID));
            }
            else
            {
                Logger.Information($"Publishing OrderStockAvailableEvent for order : {message.requestID}");
                //we have enough stock, reserve it(theoretically) then send success event
                await _bus.Send(new OrderStockAvailableEvent(message.requestID));
            }
        }
    }
}
